import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/rating_config_data.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/widgets/dotted_line.dart';

class ServiceOrderRatingViewModel extends BaseViewModel {
  final String id;

  ServiceOrderRatingViewModel(BuildContext context, this.id) : super(context);

  double ratingScore = 5;

  String get ratingInfo {
    if (ratingScore == 0.5 || ratingScore == 1) {
      return '非常不满意';
    }

    if (ratingScore == 1.5 || ratingScore == 2) {
      return '有点不满意';
    }

    if (ratingScore == 2.5 || ratingScore == 3 || ratingScore == 3.5) {
      return '一般般';
    }

    if (ratingScore == 4 || ratingScore == 4.5) {
      return '比较满意';
    }
    return '非常满意';
  }

  String remark = "";

  Future<List<RatingConfigData>> _getRatingConfig() async {
    var json = await PostRequest.ratingConfig();
    var bean = ResponseBean.fromJson(json);
    if ("0" == bean.code) {
      var list =
          (bean.data as List).map((e) => RatingConfigData.fromJson(e)).toList();
      return list;
    } else {
      throw bean.msg ?? "";
    }
  }

  var configList = <RatingConfigItemData>[];

  Future<void> getConfigData() async {
    showLoadingState();
    try {
      var list = await _getRatingConfig();
      configList = list
          .map((e) => RatingConfigItemData(
              title: e.issueName??"",
              items: [e.optionOne??"", e.optionTwo??""],
              id: e.id.toString()))
          .toList();
      showContent();
    } catch (e) {
      print(e);
      showErrorState(NetErrorUtils.getNetError(e));
    }
  }

  List<Widget> contentWidget() {
    var list = [
      CommonText('您对本次服务满意吗？', textSize: 17, fontWeight: FontWeight.bold)
          .addToContainer(
              alignment: Alignment.center,
              margin: EdgeInsets.symmetric(vertical: 16)),
      DottedLine(
        dashWidth: 4.4,
        color: Colors.grey,
      ),
      Container(
        height: 20,
      ),
      CommonText(ratingInfo, textSize: 20, fontWeight: FontWeight.bold)
          .addToContainer(
              alignment: Alignment.center,
              margin: EdgeInsets.symmetric(vertical: 16)),
      RatingBar.builder(
        itemBuilder: (context, _) {
          return Icon(
            Icons.star,
            color: Colours.app_main,
          );
        },
        onRatingUpdate: (rating) {
          ratingScore = rating;
          notifyListeners();
        },
        allowHalfRating: true,
        initialRating: 5,
        minRating: 1,
        glow: false,
        direction: Axis.horizontal,
        wrapAlignment: WrapAlignment.center,
        itemCount: 5,
      ).addToContainer(
          alignment: Alignment.center, margin: EdgeInsets.only(bottom: 16)),
    ];

    for (var item in configList) {
      list.add(Card(
        elevation: 5,
        child: Column(
          children: [
            CommonText(item.title, fontWeight: FontWeight.bold),
            Container(
              height: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: (item.items??[])
                  .map((e) => CommonText(e,
                              textColor: item.selectItem == e
                                  ? Colors.white
                                  : Colors.black)
                          .addToContainer(
                              padding: EdgeInsets.symmetric(
                                  horizontal: 10, vertical: 4),
                              decoration: BoxDecoration(
                                  borderRadius: 20.borderRadius,
                                  color: item.selectItem == e
                                      ? Colours.app_main
                                      : Colors.grey[300]))
                          .onTap(() {
                        item.selectItem = e;
                        notifyListeners();
                      }))
                  .toList(),
            )
          ],
        ).addToContainer(
          padding: EdgeInsets.all(10),
        ),
      ));
    }

    list.add(CommonInput(
      maxLines: 5,
      isDense: true,
      padding: EdgeInsets.zero,
      hintText: '请输入评价内容',
      border: InputBorder.none,
      onChanged: (str) {
        remark = str;
      },
      keyboardType: CommonInputType.multiline,
    ).addToContainer(
        margin: EdgeInsets.symmetric(vertical: 16),
        decoration: BoxDecoration(
            color: Colors.grey[200], borderRadius: 6.borderRadius),
        padding: EdgeInsets.all(10)));

    list.add(ElevatedButton(
      onPressed: () {
        submitRating();
      },
      child: CommonText('提交', textColor: Colors.white),
      style: ButtonStyle(
          minimumSize: WidgetStateProperty.all(
            Size(double.infinity, 45),
          ),
          backgroundColor: WidgetStateProperty.all(Colours.app_main)),
    ));

    return list;
  }

  Future<void> submitRating() async {
    var configMaps = <Map>[];
    for (var item in configList) {
      if (!item.selectItem.isNullOrEmpty()) {
        configMaps.add({"configIds": item.id, "configStr": item.selectItem});
      }
    }

    showLoadingDialog(msg: '提交中...');
    try {
      var data = await PostRequest.submitRating(
          ratingScore.toString(), remark, id, configMaps);
      hideDialog();
      var bean = ResponseBean.fromJson(data);
      if ('0' == bean.code) {
        sendMessage(SendMessageEvent(MessageConfig.REFRESH_ORDER));
        showToast('评价成功');
        finish();
      } else {
        showToast(bean.msg??"");
      }
    } catch (e) {
      print(e);
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    getConfigData();
  }
}

class RatingConfigItemData {
  String selectItem = "";
  String? title;
  String? id;
  List<String>? items = [];

  RatingConfigItemData({this.title, this.items, this.id});
}
